package com.lostad.app.vert.web;

import com.lostad.app.vert.util.AppProperties;

import io.vertx.core.AbstractVerticle;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.StaticHandler;
import io.vertx.ext.web.templ.ThymeleafTemplateEngine;

/**
 * This is an example application to showcase the usage of Vert.x Web.
 *
 * In this application you will see the usage of:
 *
 * * Freemarker templates * Vert.x Web
 *
 * @author <a href="mailto:pmlopes@gmail.com>Paulo Lopes</a>
 */
public class WebVerticle extends AbstractVerticle {
	private Router router;

	public WebVerticle(Router router) {
	  this.router = router; 
	}

	@Override
	public void start() throws Exception {
		// ===============================================================================
		// router.route("/private/*").handler(RedirectAuthHandler.create(authProvider,"/loginpage.html"));
		// In order to use a template we first need to create an engine
		final ThymeleafTemplateEngine engine = ThymeleafTemplateEngine.create();
		router.route("/").handler(ctx -> {
			// we define a hardcoded title for our application
			ctx.put("name", "首页");
			// and now delegate to the engine to render it.
			engine.render(ctx, "webroot/index.html", res -> {
				if (res.succeeded()) {
					ctx.response().end(res.result());
				} else {
					ctx.fail(res.cause());
				}
			});
		});
		// 指定以statics打头的请求，定位到webroot/statics做为静态目录
		router.route("/s/*").handler(StaticHandler.create());

		router.route("/web/*").handler(ctx -> {
			// we define a hardcoded title for our application
			ctx.put("name", "Vert.x Web");
			// and now delegate to the engine to render it.
			engine.render(ctx, "webroot/templates/index.html", res -> {
				if (res.succeeded()) {
					ctx.response().end(res.result());
				} else {
					ctx.fail(res.cause());
				}
			});
		});

		router.route("/chat/*").handler(ctx -> {
			ctx.put("name", "Vert.x Web");
			ctx.put("port", AppProperties.getValue("http.port", 9000));
			engine.render(ctx, "webroot/templates/websocket/ws.html", res -> {
				if (res.succeeded()) {
					ctx.response().end(res.result());
				} else {
					ctx.fail(res.cause());
				}
			});
		});

		router.route("/tel/*").handler(ctx -> {
			ctx.put("name", "Vert.x Web");
			engine.render(ctx, "webroot/templates/telemetering/index.html", res -> {
				if (res.succeeded()) {
					ctx.response().end(res.result());
				} else {
					ctx.fail(res.cause());
				}
			});
		});
	}
}